package com.shchekoldin.juliet.packager.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class HashGenerator {

    private static final Logger logger = LoggerFactory.getLogger(HashGenerator.class);

    private final static int SIGNUM = 1;

    private final static int HEX_RADIX = 16;

    private final static String MD5 = "MD5";

    // -------------------------------------------------------
    // -                        LOGIC                        -
    // -------------------------------------------------------

    private static String generateHash(String algorithm, String inputString) {
        MessageDigest messageDigest = null;

        try {
            messageDigest = MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            logger.error("Algorithm {0} doesn't exist.", e, algorithm);
        }

        assert messageDigest != null;

        messageDigest.update(inputString.getBytes());
        BigInteger hash = new BigInteger(SIGNUM, messageDigest.digest());

        return hash.toString(HEX_RADIX);
    }

    //
    // API
    //

    public static String generateMd5(String inputString) {
        return generateHash(MD5, inputString);
    }

}
